package namespace.jcu.mobile.library.system;

import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.List;

import com.parse.GetCallback;
import com.parse.Parse;
import com.parse.FindCallback;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SaveCallback;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class NewArrivalActivity extends Activity{

	
	ArrayList<BookRecord> bookList;
	BookRecord bookUpdater;
	bookListAdapter bookAdapter;
	List<ParseObject> bookRequest;
	int position;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		Parse.initialize(this, "1GlGZQ1XWU34mHgFyDHZiZRr6HTTSWOZo2nSAowy", "GKVclKTd6TIPxLVPPbDiyvzAMoWA2XLf4ZdZYFwI");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.insert_newbook);
        
        
        bookList = new ArrayList<BookRecord>();

        
        //parse query to find latest book update
        ParseQuery query = new ParseQuery("Book");
        query.orderByDescending("createdAt");
        query.findInBackground(new FindCallback() {
            public void done(List<ParseObject> queryResult, ParseException e) {
                if (e == null) {
                    for(int i=0; i<queryResult.size(); i++)
                    {
                    	
                    	//code to display the book list when its status is available
                    	if (queryResult.get(i).getBoolean("Available_Status") == true)
                    	{
	                    	bookUpdater = new BookRecord(queryResult.get(i).getString("Title"),
	                    	queryResult.get(i).getString("Author")+" , "+
	                    	String.valueOf(queryResult.get(i).getInt("Publish_Year")),
	                    	"Currently Available", ((ParseFile) queryResult.get(i).get("Image")).getUrl().toString());
	                    	
	                    	bookList.add(bookUpdater);
                    	}
                    	
                    	
                    	//code to display the book list when its status is unavailable
                    	else
                    	{
                    		
                    		//date format (1 to display as '1st', 2 as '2nd', 3 as '3rd', etc...)
                    		String date = null;
                    		if (queryResult.get(i).getDate("Available_Date").getDate() == 1 || queryResult.get(i).getDate("Available_Date").getDate() == 31)
                    		{
                    			date = "st";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getDate() == 2 || queryResult.get(i).getDate("Available_Date").getDate() == 22)
                    		{
                    			date = "nd";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getDate() == 3 || queryResult.get(i).getDate("Available_Date").getDate() == 23)
                    		{
                    			date = "rd";
                    		}
                    		else
                    		{
                    			date = "th";
                    		}
                    		
                    		

            			//prepare each record and pass it to the arraylist
                    	bookUpdater = new BookRecord(queryResult.get(i).getString("Title"),
                    	queryResult.get(i).getString("Author")+" , "+
            			String.valueOf(queryResult.get(i).getInt("Publish_Year")), "Will Be Available On "+
                    	queryResult.get(i).getDate("Available_Date").getDate()+date+" , "+
            			getMonthForInt(queryResult.get(i).getDate("DueDate").getMonth()),
            			((ParseFile) queryResult.get(i).get("Image")).getUrl().toString());
                    	bookList.add(bookUpdater);
                    	
                    	//event log to check the query result
                    	Log.d("book", "book result = "+ queryResult.size());               		
                    	}
                    }
                }
                ListView listView = (ListView) findViewById(R.id.ListViewId);
                listView.setAdapter(bookAdapter);
                
                //display detailed information of clicked items on listview using itemclicklistener
                listView.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView<?> arg0, View view, int arg2,long itemID) {

                        position = arg2;
                        setContentView(R.layout.book_detail);
                        ParseQuery query = new ParseQuery("Book");
                        query.orderByDescending("createdAt");
                        query.findInBackground(new FindCallback() {
                            public void done(List<ParseObject> queryResult, ParseException e) 
                            {
                                if (e == null)
                                {
                                    TextView tv = (TextView) findViewById(R.id.bookdetail);
                                    Button request = (Button) findViewById(R.id.request);
                                    LoaderImageView bookImage = (LoaderImageView) findViewById(R.id.loaderImageView);
                                    
                                    
                                    //code to function when the book status is available
                                    if (queryResult.get(position).getBoolean("Available_Status") == true)
                                    {
                                    	String s = "Status - Currently Available";
                                    	tv.setText(Html.fromHtml("<big><b>"+queryResult.get(position).getString("Title")+
                                    	"</b></big><br><br>Author - "+queryResult.get(position).getString("Author")+
                                    	"<br><br>Year - "+queryResult.get(position).getInt("Publish_Year")+"<br><br>"+
                                    	s+ "<br><br>ISBN - "+ queryResult.get(position).getString("ISBN")));
                                    	bookImage.setImageDrawable(((ParseFile) queryResult.get(position).get("Image")).getUrl().toString());
                                    	request.setVisibility(1);
                                    	request.setClickable(true);		//'Request' button to be clickable for the book is available
                                    	bookRequest = queryResult;
                                    	
                                    	//action on book request (clicked on "Request Button")
                                    	request.setOnClickListener(new OnClickListener() {
                                        	
                                        	public void onClick(View v) {
                                        		
                                        		//Check whether user is logged in or not
                                        		ParseUser currentUser = ParseUser.getCurrentUser();
                                        		
                                        		//code to function when user is already signed in
                                        		if (currentUser != null) {
                                            		
                                        			//display toast message when book reserve status is not available (i.e. user is not able to reserve for other user has already booked) 
                                        			if (bookRequest.get(position).getBoolean("ReservedStatus") == false)
                                            		{
                                                		Context context = getApplicationContext();
                                                		CharSequence text = "Sorry, someone may have already reserved this item.";
                                                		int duration = Toast.LENGTH_LONG;		//time duration to display toast message
                                                		
                                                		//toast message to display when the item is clicked
                                                		Toast toast = Toast.makeText(context, text, duration);
                                                		toast.show();
                                            		}
                                        			
                                        			//book status update here when book is able to be requested
                                            		else
                                            		{
                                            			String requestedBook = bookRequest.get(position).getObjectId();		//retrieve the bookID of selected item
                                            			
                                            			//retrieve the selected item by its objectId
                                            			ParseQuery query = new ParseQuery("Book");
                                            			query.getInBackground(requestedBook, new GetCallback() {
                                            			  public void done(final ParseObject object, ParseException e) {
                                            				  
                                            				//if the book exists
                                            			    if (e == null) {
                                            			    	
                                            			    	//updating book properties 
                                            			    	object.saveInBackground(new SaveCallback() {
                                            			    		  public void done(ParseException e) {
                                            			    			object.put("ReservedStatus", false);
                                            			    			object.put("ReserveeId", ParseUser.getCurrentUser().getObjectId());
                                            			    		    object.saveInBackground();		//update the data to Parse database
                                            			    		  }
                                            			    		});
                                            			    } 
                                            			    
                                            			    //if book doesn't exist
                                            			    else {
                                            			    	//log error message
                                            			      Log.e("Error", e.getMessage());
                                            			    }
                                            			  }
                                            			});
                                            			
                                            			
                                                		Context context = getApplicationContext();
                                                		CharSequence text = "You've Successfully Reserved This Item. And You'll Get Notified As Soon As the Book is Available.";
                                                		int duration = Toast.LENGTH_LONG;

                                                		
                                                		//toast message to display when the item is clicked
                                                		Toast toast = Toast.makeText(context, text, duration);
                                                		toast.show();
                                            		}                                        		
                                        		}
                                        		
                                        		//redirecting to login page if user hasn't logged in yet
                                        		else 
                                        		{
                                        			
                                            		Context context = getApplicationContext();
                                            		CharSequence text = "You must log in to request this item.";
                                            		int duration = Toast.LENGTH_LONG;

                                            		
                                            		//toast message to display when the item is clicked
                                            		Toast toast = Toast.makeText(context, text, duration);
                                            		toast.show();
                                            		
                                        		    Intent i = new Intent(getBaseContext(), LoginActivity.class);
                                        		    startActivity(i);		//call HomeActivity class to run
                                        		}


                                        	}
                                        });
                                    }
                                    
                                    //book detail to display with "Request" button unclickable when book is not available
                                    else
                                    {
                                    	String s = "Status - Currently Unavailable";
                                    	tv.setText(Html.fromHtml("<big><b>"+queryResult.get(position).getString("Title")+
                                    	"</b></big><br><br>Author - "+queryResult.get(position).getString("Author")+
                                    	"<br><br>Year - "+queryResult.get(position).getInt("Publish_Year")+"<br><br>"+
                                    	s + "<br><br>ISBN - "+ queryResult.get(position).getString("ISBN")));
                                    	bookImage.setImageDrawable(((ParseFile) queryResult.get(position).get("Image")).getUrl().toString());
                                    	request.setVisibility(1);
                                    	request.setEnabled(false);	//"Request" button to disable for the book is occupied
                                    }
                                }
                                else 
                                {
                                	Log.d("Error", e.getMessage());		//error message returned in logcat
                                }

                            }
                        });
                    }
                });

            }
        });
        bookAdapter = new bookListAdapter(this, android.R.layout.simple_list_item_1, bookList);


    }
	
	
	//convert month number into month name 
	String getMonthForInt(int m) {
	    String month = "invalid";
	    DateFormatSymbols dfs = new DateFormatSymbols();
	    String[] months = dfs.getMonths();
	    if (m >= 0 && m <= 11 ) {
	        month = months[m];
	    }
	    return month;
	}	
	

	//inner class bookListAdapter of integrating the listadapter with arrays of bookrecord
	public class bookListAdapter extends ArrayAdapter<BookRecord> {
		private ArrayList<BookRecord> bookList;

		public bookListAdapter(Context context, int textViewResourceId, ArrayList<BookRecord> bookList) {
			super(context, textViewResourceId, bookList);
			this.bookList = bookList;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.list_newbook, null);
			}
			
			BookRecord bookrecord = bookList.get(position);
			if (bookrecord != null) {
				TextView title = (TextView) v.findViewById(R.id.title);
				TextView author = (TextView) v.findViewById(R.id.author);
				TextView available_status = (TextView) v.findViewById(R.id.availableStatus);
				LoaderImageView image = (LoaderImageView) v.findViewById(R.id.loaderImageView);
				image.setImageDrawable(bookrecord.imageUrl);
				
			
				if (title != null) {
					title.setText(bookrecord.title);
				}

				if(author != null) {
					author.setText(bookrecord.author );
				}
				
				if(available_status != null) {
					available_status.setText(bookrecord.status);
				}
				
				
			}
			return v;
		}
	}
	
	//inner class to create a bookrecord
	public class BookRecord {
		public String title;
		public String author;
		public String status;
		public String imageUrl;
		
		public BookRecord(String title, String author, String status, String imageUrl) {
			this.title = title;
			this.author = author;
			this.status = status;
			this.imageUrl = imageUrl;
		}
	}
}
